import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, ajax, toast, getMultiLang } from 'nc-lightapp-front';
import { initTemplate } from './events';
import './index.less';
import SelfDocTable from '../table';
import SelfExecute from '../search';
import { actions } from '../consts.js';
import TransExecCacheUtil from '../utils/TransExecCacheUtil';
import cacheUtils from '../../trransferHistory/utils/cacheUtils.js';
const treeId = 'selfExecute';
class SyncTree extends Component {
	constructor(props) {
		super(props);
		let { form, button, table, search, syncTree } = this.props;
		let { setSyncTreeData } = syncTree;
		this.setSyncTreeData = setSyncTreeData; //设置树根节点数据方法
		let data = [];
		this.newTree = syncTree.createTreeData(data); //创建树 组件需要的数据结构
		this.state = {
			pk_accountingbook: '',
			selectedValue: '',
			mainData: {}, //主数据
			selectedItem: {
				//子表数据
				transcode: '',
				transname: '',
				pk_upertrans: '',
				transperms: [
					{
						iscorppublic: 'Y',
						pk_user: ''
					}
				],
				pk_accountingbook: 'sysinit'
			},
			user: {
				refname: '',
				refpk: ''
			},
			saveData: {},
			stateType: '1',
			tabState: '',
			configs: {}, //人员参照
			tableData: [], //表格数据
			json: {},
			transPorj:''
		};
		this.cacheUtil = new TransExecCacheUtil(this.props.ViewModel);
	}
	componentWillMount() {
		// let callback= (json) =>{
		// 	this.setState({
		// 		json:json,
		// 	},()=>{		  
		// 		initTemplate.call(this, this.props);
		// 	})
		// }
		// getMultiLang({moduleId:'20020SDTREPAGE',domainName:'gl',currentLocale:'simpchn',callback});
	}
	componentDidMount() {
		let callback= (json) =>{
			let tableData = cacheUtils.getTableData() || [];
			this.setState({
				json:json,
				tableData
			},()=>{		  
				initTemplate.call(this, this.props);
			})
		}
		getMultiLang({moduleId:'20020SDTREPAGE',domainName:'gl',currentLocale:'simpchn',callback});
	}
	componentWillUpdate() {}

	setTreeDisabled = (disabled) => {
		this.props.syncTree.setNodeDisable(treeId, disabled);
	};

	//获取初始数据
	getInitData = (pk) => {
		let data = {
			pk_accountingbook: pk ? pk : '' //核算账簿主键，若为集团默认值为 sysinit
		};
		let self = this;
		/* 去除分类信息缓存，若要加缓存需要考虑切换核算账簿时重新请求数据 */
		let chacheTreeData = cacheUtils.getTreeData()
		let factorRoot = [
			{
				title: this.state.json['20020SDTREPAGE-000034'],/* 国际化处理： 结转分类*/
				refname: this.state.json['20020SDTREPAGE-000034'],/* 国际化处理： 结转分类*/
				refpk: 'root',
				innercode: '',
				nodeData: {},
				children: []
			}
		];
		// let chacheTreeData;
		if(chacheTreeData && chacheTreeData.length>0){
			self.setSyncTreeData(treeId, chacheTreeData)
		} else {
			// 查询自定义结转分类定义（左树）
			let url = '/nccloud/gl/voucher/queryTransferType.do';
			ajax({
				url,
				data,
				success: function(response) {
					const { data, error, success } = response;
					if (success && data) {
						self.setState({
							mainData: data
						});
						self.newTree = self.dealTreeData(data.nodes.children);
						factorRoot[0].children = self.newTree;
						cacheUtils.setTreeData(factorRoot)

						setTimeout(() => {
							self.setSyncTreeData(treeId, factorRoot);
							self.props.syncTree.openNodeByPk(treeId, 'root')
							// self.onProjectChanged();
						}, 300);
					} else {
					}
				}
			});
		}
		
		// if (pk) {
			self.loadAllTransDef(pk);
		// }
	};
	// 查询自定义转账定义(右表)
	loadAllTransDef = (pk_accountingbook,pk_unit='') => {
		let page = this;
		let url = actions.queryTransForExec;
		let data = { 
			pk_accountingbook,
			pk_unit:pk_unit
		};
		ajax({
			url,
			data,
			success: function(response) {
				let { success, data, error } = response;
				if (success) {
					page.cacheUtil.setAllTransDef(data);
					let selectInfo = page.props.syncTree.getSelectNode(treeId)
					page.onSelectEve(null, selectInfo, null)
				} else {
					toast({ content: error.message, color: 'warning' });
				}
			}
		});
	};
	// 选中左树节点回调（渲染右表）
	onSelectEve(data, item, isChange) {
		let page = this;
		const tableData = [];
		let tempData = page.cacheUtil.getAllTransDef();
		const pkSortsMap = {};
		this.extractSortPkFromNode(item, pkSortsMap);
		if (tempData) {
			tempData.map((item) => {
				if (pkSortsMap[item.pk_transsort]) {
					tableData.push(item);
				}
			});
		}
		page.setState({ tableData });
		cacheUtils.setTableData(tableData)
	}

	extractSortPkFromNode(node, pkMap) {
		if (node) {
			pkMap[node.refpk] = node;
			if (node.children && node.children.length > 0) {
				node.children.map((item) => {
					this.extractSortPkFromNode(item, pkMap);
				});
			}
		}
	}
	// 切换执行方案
	onProjectChanged = (transPorj) => {
		let page = this;
		page.setState({ tableData: [] });
		cacheUtils.setTableData([])
		let treeData = cacheUtils.getTreeData();
		if (transPorj) {
			if(treeData){
				page.props.syncTree.setNodeDisable(treeId, true);
			}
			page.loadTransDefByProj(transPorj);	
		} else {
			if(treeData){
				page.props.syncTree.setNodeDisable(treeId, false);
				let selectInfo = page.props.syncTree.getSelectNode(treeId)
				page.onSelectEve(null, selectInfo, null)
				page.setState({ 
					transPorj: ''
				});
			}
		}
	};
	// 加载按方案执行的数据
	loadTransDefByProj = (pk_transPorj) => {
		let page = this;
		let { pk_accountingbook } = page.state;
		let url = actions.queryTransByProj;
		let data = { pk_project: pk_transPorj, pk_accountingbook };		
		ajax({
			url,
			data,
			success: function(response) {
				let { success, error, data } = response;
				if (success) {
					if (!data) {
						data = [];
					}
					page.setState({ 
						tableData: data,
						transPorj: pk_transPorj
					});
					cacheUtils.setTableData(data)
				} else {
					toast({ content: error.message, color: 'warning' });
				}
			}
		});
	};

	// 获取选中数据
	getCheckedData() {
		let checkedData = this.SelfDocTable.getCheckedData();
		return checkedData;
	}

	// 更新按钮状态
	updateButtonStatus(disabled,isProject) {
		this.SelfExecute.updateButtonStatus(disabled,isProject)
	}
	
	getPK = (data) => {
		//获取选中账簿
		this.setState({
			pk_accountingbook: data,
			tableData: []
		});
		cacheUtils.setTreeData([])
		this.getInitData(data);
	};
	dealTreeData(data) {
		//去null
		let deleteDataChildrenProp = function(node) {
			if (!node.children || node.children.length == 0) {
				delete node.children;
			} else {
				node.isLeaf = false;
				node.children.forEach((e) => {
					deleteDataChildrenProp(e);
				});
			}
		};
		let joinCodeAndName = function(node){
			if(node){
				node.title = node.innercode + " " + node.refname;
				node.refname = node.innercode + " " + node.refname;
				if(node.children){
					node.children.map((item) => {
						joinCodeAndName(item);
						return item;
					});
				}
			}
		}
		if (data) {
			data.forEach((e) => {
				deleteDataChildrenProp(e);
				joinCodeAndName(e);
			});
		}
		return data;
	}

	render() {
		const { syncTree,  DragWidthCom } = this.props;		
		let { createSyncTree } = syncTree;
		let { tableData, transPorj, json } = this.state;
		return (
			<div className='nc-bill-tree-table selfExecute'>
				<SelfExecute
					getPK={this.getPK.bind(this)}
					json = {json}
					getCheckedData={this.getCheckedData.bind(this)}
					onProjectChanged={this.onProjectChanged}
					loadAllTransDef={this.loadAllTransDef}	
					SelfExecuteRef={(init) => {this.SelfExecute = init;}}
					{...this.props}
				/>
				<div className='tree-table-container'>
					<div className="tree-table" style={{height: '100%'}}>
						<DragWidthCom
							defLeftWid={'280px'}
							leftDom={<div className='tree-area'>
								{createSyncTree({
									treeId: treeId,
									showLine: true,
									showModal: false, //是否使用弹出式编辑
									needSearch: false, //是否需要查询框，默认为true,显示。false: 不显示
									needEdit: false,
									selectedForInit: true, //默认选中第一个子节点
									onSelectEve: this.onSelectEve.bind(this) //选择节点回调方法
								})}
							</div>}
							rightDom={
								<SelfDocTable
									mainData={tableData}
									transPorj={transPorj}
									updateButtonStatus={this.updateButtonStatus.bind(this)}
									SelfDocTableRef={(init) => {
										this.SelfDocTable = init;
									}}
								/>
							}
						/>
					</div>
				</div>
			</div>
		);
	}
}

SyncTree = createPage({
	// initTemplate: initTemplate
})(SyncTree);

export default SyncTree;
